package es.castorm.business.customer.internal;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import org.springframework.beans.factory.annotation.Autowired;

import es.castorm.arch.web.ExtJsResponse;
import es.castorm.arch.web.WebResource;
import es.castorm.business.customer.CustomerCriteriaDTO;
import es.castorm.business.customer.CustomerDTO;
import es.castorm.business.customer.CustomerService;

@WebResource
@Path("/customer")
public class CustomerResource {

	@Autowired
	CustomerService customerService;

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public ExtJsResponse<List<CustomerDTO>> find(@Context UriInfo info) {
		try {
			CustomerCriteriaDTO criteria = new CustomerCriteriaDTO();
			criteria.setFirstname(info.getQueryParameters().getFirst("firstname"));
			criteria.setLastname(info.getQueryParameters().getFirst("lastname"));
			criteria.setEmail(info.getQueryParameters().getFirst("email"));
			return new ExtJsResponse<List<CustomerDTO>>(customerService.findCustomers(criteria));
		} catch (Exception e) {
			return new ExtJsResponse<List<CustomerDTO>>(null, e.getMessage());
		}
	}

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public ExtJsResponse<CustomerDTO> create(CustomerDTO customer) {
		try {
			return new ExtJsResponse<CustomerDTO>(customerService.createCustomer(customer));
		} catch (Exception e) {
			return new ExtJsResponse<CustomerDTO>(customer, e.getMessage());
		}
	}

	@PUT
	@Path("/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public ExtJsResponse<CustomerDTO> update(CustomerDTO customer) {
		try {
			return new ExtJsResponse<CustomerDTO>(customerService.updateCustomer(customer));
		} catch (Exception e) {
			return new ExtJsResponse<CustomerDTO>(customer, e.getMessage());
		}
	}

	@DELETE
	@Path("/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public ExtJsResponse<CustomerDTO> delete(CustomerDTO customer) {
		try {
			customerService.deleteCustomer(customer);
			return new ExtJsResponse<CustomerDTO>(null);
		} catch (Exception e) {
			return new ExtJsResponse<CustomerDTO>(null, e.getMessage());
		}
	}
}
